﻿using System;
using Coder.Workflow;
using Identity;
using Text.Helper;

namespace Coder.Workflow
{
    public class WorkActivity
    {
        public WorkActivity()
        {
            CreateTime = DateTime.Now;
        }

        //   public string Name { get; set; }
        public int Id { get; set; }
        public ProcessInstance ProcessInstance { get; set; }

        public Role Role { get; set; }
        public WorkTask WorkTask { get; set; }
        public WorkActivityStatus Status { get; protected set; }
        public User DepositUser { get; set; }
        public DateTimeOffset? DepositTime { get; protected set; }

        public DateTimeOffset CreateTime { get; protected set; }

        /// <summary>
        /// </summary>
        public DateTimeOffset? AssignTime { get; set; }

        public string Comment { get; set; }

        public byte[] TimeSpan { get; protected set; }

        public void AssignTo(User user)
        {
            if (Status != WorkActivityStatus.UnAssign)
                throw new WorkflowException("只有状态为" + WorkActivityStatus.UnAssign.GetEnumDisplayName() +
                                            "才能进行分配工单。");
            AssignTime = DateTimeOffset.Now;
            DepositUser = user ?? throw new ArgumentNullException(nameof(user));
            Status = WorkActivityStatus.Processing;
        }

        public void Giveup(User user = null)
        {
            if (user != null && DepositUser.Id != user.Id)
                throw new WorkflowException("你无权改这个工单的执行人");

            if (Status != WorkActivityStatus.Processing)
                throw new WorkflowException("只有状态为" + WorkActivityStatus.Processing.GetEnumDisplayName() +
                                            "才能放弃工单工单。");
            AssignTime = null;
            DepositUser = null;
            Status = WorkActivityStatus.UnAssign;
        }

        /// <summary>
        ///     已经解决，下一步
        /// </summary>
        public virtual void Resolve(string comment)
        {
            if (DepositUser == null) throw new UnassignmentWorkflowException();

            if (Status != WorkActivityStatus.Processing)
                throw new WorkflowException("只有处理中的才能同意进入下一步，现在状态是" + Status);

            Comment = comment;
            Status = WorkActivityStatus.Resolve;
            DepositTime = DateTimeOffset.Now;
        }

        /// <summary>
        ///     拒绝，返回上一步
        /// </summary>
        /// <param name="comment"></param>
        /// <param name="nextInstanceActivity"></param>
        /// <returns></returns>
        public void Reject(string comment)
        {
            if (DepositUser == null) throw new UnassignmentWorkflowException();

            if (Status != WorkActivityStatus.Processing)
                throw new WorkflowException("只有处理中的才能 否决 ，但现在状态是" + Status);


            Status = WorkActivityStatus.Reject;
            DepositTime = DateTimeOffset.Now;

            Comment = comment;
        }
    }
}